<template>
  <el-dialog :title="showTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeFn">
    <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="form.description" placeholder="请输入角色描述" />
      </el-form-item>
    </el-form>

    <el-row type="flex" justify="center">
      <el-button @click="closeFn">取消</el-button>
      <el-button type="primary" @click="btnOk">确认</el-button>
    </el-row>

  </el-dialog>
</template>
<script>
import { addRoleApi, getRoleDetailApi, editRoleApi } from '@/api/setting'
export default {
  name: 'AddDialog',
  data() {
    return {
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '修改角色' : '新增角色'
    }
  },
  created() {
  },
  methods: {
    // 关闭dialog 弹框
    closeFn() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新增用户
    async btnOk() {
      // 1.兜底校验
      await this.$refs.roleForm.validate()
      try {
        // ! 通过form.id判断是编辑还是新增
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('修改成功')
        } else {
          // 2.发送请求
          await addRoleApi(this.form)
          // 3.成功提示
          this.$message.success('添加成功')
        }
        // 4.清空表单
        this.closeFn()
        // 5.刷新数据
        this.$emit('updata')
      } catch (error) {
        return console.log(error)
      }
    },
    // 编辑时，表单数据回显
    async getRoleDetail(ID) {
      this.showDialog = true
      const res = await getRoleDetailApi(ID)
      this.form = res.data
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
